<template lang="pug">
.search-box(:class="prop")
    .label(v-if="label") {{label}}
    .input-box(:class="{'date-picker-range':type=='pickerRange',textarea:type=='textarea',readonly:readonly||disabled}")
        el-input-number(v-if="type=='inputnumber'" controls-position="right" :id="prop" :precision="precision" :maxlength="maxlength" v-model="value" :title="readonly?value:''"  :min="min" :max="max" :disabled="disabled" :readonly="readonly" @input="handleChange"  @change="handleChange")
        .dbinputnumbe(v-if="type == 'dbinputnumber'")
            el-input-number(:id="prop" :maxlength="maxlength" controls-position="right" :precision="precision" v-model="startNumber" :min="min" :max="max" :disabled="disabled" :readonly="readonly" @input="handleChange"  @change="handleChange")
            span ~
            el-input-number(:id="prop" :maxlength="maxlength" controls-position="right" :precision="precision" v-model="endNumber" :min="min" :max="max" :disabled="disabled" :readonly="readonly" @input="handleChange"  @change="handleChange")

        el-input(v-if="type=='input'" :id="prop" :size="size" :maxlength="maxlength" v-model="value" :title="readonly?value:''" :placeholder="placeholder||'请输入'" :disabled="disabled" :readonly="readonly" :clearable="clearable" @input="handleChange"  @change="handleChange")
            slot(slot="append" name="append")
        el-input(v-if="type=='textarea'" type="textarea" :maxlength="maxlength"  v-model="value" :placeholder="placeholder||'请输入'" :disabled="disabled" :readonly="readonly" @input="handleChange"  @change="handleChange")
        el-input(v-if="type=='password'" type="password" :maxlength="maxlength"  v-model="value" :id="prop" :placeholder="placeholder||'请输入'" :disabled="disabled" :readonly="readonly" @input="handleChange"  @change="handleChange")
        el-select(v-if="type=='select'"  v-model="value" :filterable="filterable" :remote="remote" :loading="loading" :remote-method="remoteMethod" :placeholder="placeholder||'请选择'"  :clearable="clearable" :disabled=" disabled|| readonly"  @input="handleChange"  @change="handleChange")
            el-option(v-for="item in option" :key="item.value||item.label" :label="item.label" :value="item.value||item.label" :disabled="item.disabled")
        el-select(v-if="type=='selectmultiple'"  multiple v-model="value" :placeholder="placeholder||'请选择'" :disabled=" disabled|| readonly" :clearable="clearable" @input="handleChange"  @change="handleChange")
            el-option(v-for="item in option" :key="item.value||item.label" :label="item.label" :value="item.value||item.label")
        el-tree-select(v-if="type=='treeSelect'" :data="option" filterable v-model="value" :placeholder="placeholder||'请选择'" :disabled=" disabled|| readonly" :clearable="clearable" @input="handleChange"  @change="handleChange")
        el-date-picker(v-if="type=='datePicker'" ref="dataPicker" :editable="editable" :type="pickerType" :pickerOptions="pickerOptions" v-model="value" :disabled="disabled" :readonly="readonly"  :placeholder="placeholder||'请选择日期'" :value-format="valueFormat" :clearable="clearable" @input="handleChange"  @change="handleChange")
        .datePickerRange(v-if="type=='pickerRange'")
            el-date-picker(:type="pickerType"  ref="dataPicker0" :editable="editable" v-model="startValue" :placeholder="startPlaceholder" :value-format="valueFormatCopy" :disabled="disabled" :readonly="readonly"  :clearable="clearable" @input="handleChange"  @change="handleChange")
            span ~
            el-date-picker(:type="pickerType"  ref="dataPicker1" :editable="editable" v-model="endValue" :placeholder="endPlaceholder" :value-format="valueFormatCopy"  :disabled="disabled" :readonly="readonly" :clearable="clearable" @input="handleChange"  @change="handleChange")
        el-radio-group(v-if="type=='radio'" v-model="value" @change="handleChange" :disabled="disabled" :readonly="readonly")
            el-radio(v-for="item in option" :key="item.value" :label="item.value" :disabled="disabled" :readonly="readonly") {{item.label}}
        .check-all(v-if="type=='checkboxall'")
            el-checkbox(
                v-model="checkAll"
                :disabled="disabled"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange()"
                ) 全选
            span.checkedNumber 已选 {{valueArrAll.length}} 个
            el-checkbox-group(
                v-model="valueArrAll"
                @change="handleCheckedChange()"
            )
                el-checkbox(v-for="item in option" :key="item.value" :label="item.value" :value="item.value" :disabled="disabled" :readonly="readonly") {{item.label}}

        el-checkbox-group(v-if="type=='checkbox'" v-model="valueArr" @change="handleChange")
            el-checkbox(v-for="item in option" :key="item.value" :label="item.value" :value="item.value" :disabled="disabled" :readonly="readonly") {{item.label}}
        el-cascader(v-if="type=='cascader'" v-model="value" :options="option" @change="handleChange" :props="defaultProps")
</template>
<script  setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
    size: {
        type: String,
        default: ''
    },
    editable: { //el-date-picker 编辑按钮
        type: Boolean,
        default: false
    },
    filterable: { //select搜索
        type: Boolean,
        default: false
    },
    type: {
        type: String,
        default: 'input'
    },
    pickerType: { //date week  month year
        type: String,
        default: 'date'
    },
    maxlength: {
        type: Number,
        default: 1000
    },
    min: {
        type: Number,
        default: 0
    },
    max: {
        type: Number,
        default: 99999
    },
    prop: {
        type: String,
        default: ''
    },
    clearable: {
        type: Boolean,
        default: true
    },
    disabled: {
        type: Boolean,
        default: false
    },
    readonly: {
        type: Boolean,
        default: false
    },
    defaultValue: {
        type: null,
        default: null
    },
    label: {
        type: String,
        default: ''
    },
    placeholder: {
        type: String,
        default: ''
    },
    startPlaceholder: {
        type: String,
        default: '起始日期'
    },
    endPlaceholder: {
        type: String,
        default: '结束日期'
    },
    loading: { //
        type: Boolean,
        default: false
    },
    remote: { //远程搜索
        type: Boolean,
        default: false
    },
    remoteMethod: { //远程搜索函数
        type: Function,
        default: null
    },
    option: {
        type: Array,
        default: function(){
            return []
        }
    },
    defaultProps: {
        type: Object,
        default: function(){
            return {}
        }
    },
    pickerOptions: {
        type: Object,
        default: function(){
            return {}
        }
    },
    valueFormat: {
        type: String,
        default: 'YYYY-MM-DD'
    },
    precision: {
        type: Number,
        default: 0
    }
})
//定义属性
const value = ref('')
const valueArr = ref([])

const startValue = ref('')
const endValue = ref('')

const startNumber = ref(1)
const endNumber = ref(1)

const valueFormatCopy = ref('YYYY-MM-DD')
const valueArrAll = ref([])
const checkAll = ref(false)
const isIndeterminate = ref(false)

const emit = defineEmits(['handleChange'])
const handleCheckAllChange = () => {//全选
    valueArrAll.value = checkAll.value ? props.option.map((v)=>v.value) : []
    isIndeterminate.value = false
    handleChange()
}
const handleCheckedChange = () => {//单选
    const checkedCount = valueArrAll.value.length
    checkAll.value = checkedCount === props.option.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < props.option.length
    handleChange()
}
//定义方法
const handleChange = () =>{
    let val = value.value
    if (props.type == 'dbinputnumber'){
        val = [startNumber.value || '', endNumber.value || '']
    }
    if (props.type == 'pickerRange'){
        val = [startValue.value || '', endValue.value || '']
    }
    if (props.type == 'selectmultiple'){
        val = value.value && value.value.join(',')
    }
    if (props.type == 'checkbox'){
        val = valueArr.value || []
    }
    if (props.type == 'checkboxall'){
        val = valueArrAll.value
    }
    emit('handleChange', { label: props.label, prop: props.prop, value: val, type: props.type })
}

watch(()=>props.option, (n, o)=>{
    if(props.type == 'checkboxall'){
        if(props.option.length > 0 && props.defaultValue && props.defaultValue.length > 0){
            let arr = []
            props.option.forEach((val) => {
                props.defaultValue.forEach((v) => {
                    if(val.value == v){
                        arr.push(v)
                    }
                })
            })
            valueArrAll.value = arr
            //全选
            if(props.option.length == arr.length){
                checkAll.value = true
            }
        }else{
            valueArrAll.value = []
        }
        checkAll.value = false
        isIndeterminate.value = false
        if(n.length > 0){
            handleCheckedChange()
        }
        emit('handleChange', { label: props.label, prop: props.prop, value: valueArrAll.value })
    }
    if(props.type == 'checkbox' || props.type == 'select' || props.type == 'treeSelect' || props.type == 'radio' || props.type == 'cascader'){
        if(props.type == 'select' && props.remote){//带远程搜索的select option随时变化,value不能清空
        }else{
            value.value = props.defaultValue || ''
        }
        emit('handleChange', { label: props.label, prop: props.prop, value: value.value })
    }
}, { immediate: true })

watch(()=>props.pickerType, (n, o)=>{
    if (n == 'date'){
        valueFormatCopy.value = props.valueFormat
    } else if (n == 'year'){
        valueFormatCopy.value = 'YYYY'
    }
    handleChange()
}, { immediate: true })

watch(()=>startValue, (n, o)=>{
    if (n && endValue.value && new Date(n).getTime() > new Date(endValue.value).getTime()){
        startValue.value = ''
        ElMessage({
            message: '起始时间不能大于结束时间',
            type: 'warning'
        })
    }
})
watch(()=>endValue, (n, o)=>{
    if (n && startValue.value && new Date(n).getTime() < new Date(startValue.value).getTime()){
        endValue.value = ''
        ElMessage({
            message: '结束时间不能小于起始时间',
            type: 'warning'
        })
    }
})
watch(()=>startNumber.value, (n, o)=>{
    // if (startNumber.value > endNumber.value){
    //     setTimeout(()=>{
    //         endNumber.value = startNumber.value
    //     })
    // }
})
watch(()=>endNumber.value, (n, o)=>{
    // if (startNumber.value > endNumber.value){
    //     setTimeout(()=>{
    //         startNumber.value = endNumber.value
    //     })
    // }
})
//watch
watch(()=>props.defaultValue, (n, o)=>{
    if (props.type == 'checkbox'){
        valueArr.value = n || []
    } else if (props.type == 'checkboxall'){
        valueArrAll.value = n || []
    } else if (props.type == 'dbinputnumber'){
        startNumber.value = props.defaultValue[0]
        endNumber.value = props.defaultValue[1]
    } else {
        value.value = n
    }
    handleChange()
}, { immediate: true })


const valueInt = (val, core)=>{
    if (props.type == 'checkbox'){
        valueArr.value = val || props.defaultValue || []
    } else {
        value.value = val || props.defaultValue
        startValue.value = val || props.defaultValue
        endValue.value = val || props.defaultValue
    }
    if (props.defaultValue){
        handleChange()
    }
}


defineExpose({
    valueInt
})
</script>
<style lang="less" scoped>
.search-box{
    display: flex;
    align-items: center;
    .label{
        min-width: 90px;
        text-align: right;
        white-space: nowrap;
        color: #fff;
        font-size: 14px;
        margin-right: 10px;
    }
    .input-box{
        width: 140px;
        &.readonly{
            :deep(input){
                // background: #eaeaea;
                color: #a2a3a4;
            }
        }
    }
    .datePickerRange{
        display: flex;
        align-items: center;
        span{
            margin: 0 4px;
        }
        :deep(.el-input__prefix){
            display: none;
        }
        :deep(.el-input__icon){
            width: 12px;
        }
    }
    :deep(.el-date-editor.el-input){
        width: 100%;
    }
    :deep(textarea){
        resize: none;
        height: 96px;
    }
    :deep(.el-select.el-select--small){
        width: 100%;
    }
    :deep(.el-input-group){
        vertical-align: baseline;
    }
}
.dbinputnumbe{
    display: flex;
    align-items: center;
    justify-content: space-between;
    span{
        margin: 0 5px;
    }
}
:deep(.el-input-number){
    width: 100%;
}
.checkedNumber{
    font-size: 12px;
    margin-left: 10px;
    color: #ccc;
}
:deep(.el-checkbox-group .input-box){
    width: 100% !important;
}

</style>